#include "unp.h"
#include <semaphore.h>


#define NBUFF 10
#define SEM_MUTEX   "mutex"
#define SEM_NEMPTY  "nempty"
#define SEM_NSTORED "nstored"

int nitems;
struct {
  int buff[NBUFF];
  sem_t *mutex,*nempty,*nstored;
} shared;


void *produce(void*),*consume(void*);

int main(int argc,char* argv[])
{
   pthread_t tid_produce,tid_consume;
   
   if(argc != 2)
       err_sys("Usage: prodcons1 <#items>");
   
   nitems = atoi(argv[1]);

   shared.mutex = sem_open(SEM_MUTEX,O_CREAT|O_EXCL,FILE_MODE,1);
   if(shared.mutex == SEM_FAILED){
     if(errno != EEXIST)
       err_sys("sem_open SEM_MUTEX error");
   }
      
   shared.nempty = sem_open(SEM_NEMPTY,O_CREAT|O_EXCL,FILE_MODE,NBUFF);
   if(shared.nempty == SEM_FAILED){
     if(errno != EEXIST)
       err_sys("sem_open SEM_NEMPTY error");
   }
 
   shared.nstored = sem_open(SEM_NSTORED,O_CREAT|O_EXCL,FILE_MODE,0);
   if(shared.nstored == SEM_FAILED){
     if(errno != EEXIST)
       err_sys("sem_open SEM_NSTORED error");
   }
  
   int err; 
   if((err=pthread_create(&tid_produce,NULL,produce,NULL)) != 0)
      err_sys("pthread_create produce err"); 
   if((err=pthread_create(&tid_consume,NULL,consume,NULL)) != 0)
      err_sys("pthread_create consume err"); 

   //int ret; 
   pthread_join(tid_produce,NULL);
   pthread_join(tid_consume,NULL);

   sem_unlink(SEM_MUTEX);
   sem_unlink(SEM_NEMPTY);
   sem_unlink(SEM_NSTORED);
   return 0;
}
